<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2019/09/04
 * Time: 17:52
 */

namespace Modules\Shop\Service;

use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\OrderPayRefundRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\OrderRepairstoreGoodsRepository;
use HiCommon\Service\PayRefundService;
use HiCommon\Service\PayService;

class OrderRepairService
{
    /**
     * 获取分页数据
     */
    public function get_list(array $arr_search)
    {
        try {
            $map = self::check_order_status($arr_search);
            $arr_option['where'] = $map['where'];
            //$arr_option['with'] = ['shop', 'user', 'gtype'];
            $data_obj = OrderRepairstoreRepository::get_list($arr_option, $map['search']);
            $data = list_page_data($data_obj, $arr_search);

            foreach ($data['data'] as $key => &$value) {
                $value['order_status'] = OrderRepairstoreRepository::orderStatus($value['status'], $value['pay_status']);
            }
            $shop_id = $map['where']['shop_id'];
            $data['d_num'] = OrderRepairstoreRepository::get_count_by_where(['status' => 0, 'order_type' => 1, 'pay_status' => 1, 'shop_id' => $shop_id]);//待处理订单数量
            $data['t_num'] = OrderRepairstoreRepository::get_count_by_where(['status' => 0, 'order_type' => 1, 'pay_status' => 2, 'shop_id' => $shop_id]);//申请退款订单数量

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 订单状态筛选条件
     */
    public function check_order_status($arr_search)
    {
        $search = [];
        if (!empty($arr_search['order_number'])) {
            $where['order_number'] = $arr_search['order_number'];
        }
        if (!empty($arr_search['range'])) {
            $search['range'] = $arr_search['range'];
        }
        if (!empty($arr_search['range'])) {
            $search['range'] = $arr_search['range'];
        }
        if (!empty($arr_search['order_type'])) {
            $where['order_type'] = $arr_search['order_type'];
        }
        if (!empty($arr_search['order_type'])) {
            $where['shop_id'] = $arr_search['shop_id'];
        }

        if (!empty($arr_search['status']) && $arr_search['status'] == '1') {//待支付
            $where['status'] = 0;
            $where['pay_status'] = 0;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '2') {//待处理
            $where['status'] = 0;
            $where['pay_status'] = 1;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '3') {//申请退款
            $where['status'] = 0;
            $where['pay_status'] = 2;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '4') {//已退款
            $where['status'] = 0;
            $where['pay_status'] = 3;
        } elseif (!empty($arr_search['status']) && $arr_search['status'] == '5') {//已取消
            $where['status'] = 2;
        }

        return ['where' => $where, 'search' => $search];
    }

    /**
     * 保养订单列表
     */
    public function maintain_order_list(array $arr_search)
    {
        try {
            $map = self::check_order_status($arr_search);
            $search = $map['search'];

            $arr_option['where'] = $map['where'];
            //$arr_option['with'] = ['maintain_goods'];
            $data_obj = OrderRepairstoreRepository::get_list($arr_option, (array)$search);
            $data = list_page_data($data_obj, $arr_search);

            foreach ($data['data'] as $key => &$value) {
                $value['order_status'] = OrderRepairstoreRepository::orderStatus($value['status'], $value['pay_status']);
            }
            $shop_id = $map['where']['shop_id'];
            $data['d_num'] = OrderRepairstoreRepository::get_count_by_where(['status' => 0, 'order_type' => 2, 'pay_status' => 1, 'shop_id' => $shop_id]);//待处理订单数量
            $data['t_num'] = OrderRepairstoreRepository::get_count_by_where(['status' => 0, 'order_type' => 2, 'pay_status' => 2, 'shop_id' => $shop_id]);//申请退款订单数量

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 添加一条数据
     */
    public function add_one($arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            //添加
            $res = OrderRepairstoreRepository::add_one($arr_input)->toarray();
            if (empty($res)) {
                return hello_error('添加失败');
            }

            return hello_success('成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 查询一条数据
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }
            $arr_option['with'] = ['user'/*,'maintain_goods'*/];
            $order_boj = OrderRepairstoreRepository::get_one($n_id, $arr_option);
            if ($order_boj->first()) {
                $order_arr = $order_boj->toArray();
                $order_arr['state'] = OrderRepairstoreRepository::orderStatus($order_arr['status'], $order_arr['pay_status']);

                return hello_success('查询成功', $order_arr);
            }

            return hello_error('失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改一条数据
     */
    public function edit_one(array $arr_input)
    {
        $arr_input = hi_array_del_null($arr_input);
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = OrderRepairstoreRepository::edit_one($arr_input);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 修改单个字段
     */
    public function change_one_state($arr_input)
    {
        try {
            $arr_input['id'] = (int)$arr_input['id'];
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }

            if (!empty($arr_input['pay_status'] == 3)) {//退款处理
                return self::refund((int)$arr_input['id']);
            }

            if ($arr_input['status'] == 1) {
                $arr_option['field'] = ['id', 'is_online_pay', 'is_scanning_code'];
                $info = OrderRepairstoreRepository::get_one($arr_input['id'], $arr_option);
                if($info->is_scanning_code != 1){
                    return hello_error('请扫描用户端二维码确认订单');
                }

                if($info->is_online_pay == 1){
                    $arr_input['pay_time'] = date('Y-m-d H:i:s');
                }

                $arr_input['pay_status'] = 1;
                $arr_input['checked_at'] = date('Y-m-d H:i:s');//检修时间

                //消息推送
                $dataNotice = [
                    'notice_type' => 'wxby_order_message_push',
                    'order_id' => $arr_input['id'],
                    'type' => 60,
                    'title' => '处理通知',
                    'content' => '商家已确认处理'
                ];
                predis_notice_queue_in($dataNotice);
            }

            $res = OrderRepairstoreRepository::edit_one($arr_input);
            if ($res === false) {
                return hello_error('操作失败');
            }

            if (!empty($arr_input['pay_status'] == 4)) {//拒绝退款
                //消息推送
                $dataNotice = [
                    'notice_type' => 'wxby_order_message_push',
                    'order_id' => $arr_input['id'],
                    'type' => 33,
                    'title' => '拒绝退款通知',
                    'content' => '商家已拒绝退款'
                ];
                predis_notice_queue_in($dataNotice);
            }

            if (!empty($arr_input['status'] == 2)) {//取消订单
                //消息推送
                $dataNotice = [
                    'notice_type' => 'wxby_order_message_push',
                    'order_id' => $arr_input['id'],
                    'type' => 37,
                    'title' => '取消订单通知',
                    'content' => '已被商家取消'
                ];
                predis_notice_queue_in($dataNotice);

                self::backStock($arr_input['id']);
            }

            return hello_success('处理成功');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     *保养订单取消订单回收库存
     */
    public function backStock($order_id)
    {
        $arr_option['with'] = ['maintain_goods'];
        $arr_option['field'] = ['id'];
        $detail_obj = OrderRepairstoreRepository::get_one($order_id, $arr_option);

        if ($detail_obj->first() && $detail_obj->maintain_goods) {
            foreach ($detail_obj->maintain_goods as $item) {
                GoodsProductRepository::increase_num($item->product_id, 'stock', $item->goods_num);
            }
        }
    }

    /**
     * 退款处理
     */
    public function refund(int $order_id)
    {
        $order = OrderRepairstoreRepository::get_one($order_id);
        if ($order->first()) {
            $info = $order->toArray();

            $s_order_sn = $info['order_number'];//订单编号
            $s_refund_sn = $info['order_number'];//退单编号

            //退款处理
            return PayRefundService::api_online_pay_refund($s_order_sn, $s_refund_sn);
        }

        return hello_error('订单不存在');
    }

    /**
     * 删除一条数据
     *
     * @param int $n_id
     *
     * @return array|\Illuminate\Http\RedirectResponse
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function delete_one($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }

            $res = OrderRepairstoreRepository::delete_one($n_id);
            if ($res === false) {
                return hello_error('操作失败');
            }
            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 定时任务三十分钟后取消订单(回收库存)
     */
    public function api_auto_cancle_repair($data)
    {
        $arr_input = ['id' => $data['id'], 'status' => 2];
        $res = OrderRepairstoreRepository::edit_one($arr_input);
        if ($data['order_type'] == 2) {
            //回收商品库存
            self::stock_back((int)$data['id']);
        }
        if ($res === false) {
            return hello_error('取消失败');
        }

        //消息推送
        $dataNotice = [
            'notice_type' => 'wxby_order_message_push',
            'order_id' => $data['id'],
            'type' => 37,
            'title' => '取消订单通知',
            'content' => '30分钟内未支付已自动取消'
        ];
        predis_notice_queue_in($dataNotice);

        return hello_success('取消成功');
    }

    /**
     * 回收库存
     */
    public function stock_back(int $order_id)
    {
        $arr_option['where'] = ['order_repairstore_id' => $order_id];
        $arr_option['field'] = ['id', 'product_id', 'goods_num'];
        $list = OrderRepairstoreGoodsRepository::get_all($arr_option)->toArray();

        foreach ($list as $key => $value) {
            $id = $value['product_id'];
            $num = $value['goods_num'];
            GoodsProductRepository::increase_num($id, 'stock', $num);
        }
    }

    /**
     * 导出EXCEL （所有）
     */
    public function get_order_list(array $arr_search)
    {
        try {
            $map = self::check_order_status($arr_search);
            $arr_option['where'] = $map['where'];
            $search = $map['search'];
            $arr_option['with'] = ['user'];

            if ($arr_search['cate'] == '1') {
                $search['order_type'] = 1;
                $data = OrderRepairstoreRepository::get_all($arr_option, $search)->toArray();
            } else {
                $search['order_type'] = 2;
                $data = OrderRepairstoreRepository::get_all($arr_option, $search)->toArray();
            }
            $orderList = [];
            if ($data) {
                foreach ($data as $key => &$value) {
                    $value['order_status'] = OrderRepairstoreRepository::orderStatus($value['status'], $value['pay_status']);
                    $orderList[$value['order_status']][] = $value;
                }
            }

            return $orderList;
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 推送通知处理
     * @param array $data
     * @return array
     */
    public function notice_processing($data = [])
    {
        $arr_option['field'] = ['id', 'order_type', 'pay_status', 'pay_price', 'user_id', 'status', 'maintain_shop_id', 'goods_name', 'repairstore_goods_id'];
        $arr_option['with'] = ['maintain_goods', 'goods' => function ($query) {
            $query->with(['pic']);
        }];

        if (!empty($data['order_id'])) {
            $where = ['id' => $data['order_id']];
        } elseif (!empty($data['order_no'])) {
            $where = ['order_number' => $data['order_no']];
        } else {
            return hello_error('条件错误！');
        }

        $result = OrderRepairstoreRepository::get_one_by_where($where, $arr_option);
        if ($result->first()) {
            $info = $result->toarray();

            if ($info['order_type'] == 1) {//服务订单
                $goods_img = array_shift($info['goods']['pic'])['picurl']['full_src'];
                $goods_name = '您购买的【' . $info['goods']['name'];
                if (strlen($goods_name) > 50) {
                    $goods_name = mb_substr($goods_name, 0, 30) . '...';
                }
                $order_type = 2;
            } else { //保养订单
                $goods_img = array_shift($info['maintain_goods'])['get_product']['pic']['full_src'];
                $goods_name = '您购买的【' . $info['goods_name'];
                if (strlen($goods_name) > 50) {
                    $goods_name = mb_substr($goods_name, 0, 30) . '...';
                }
                $order_type = 5;
            }

            $message = [
                'img' => $goods_img,              //图片地址  string
                'title' => $data['title'],        //标题  string
                'content' => $goods_name . '】' . $data['content'],    //内容  string
                'user_id' => $info['user_id'],    //用户id   int
                'pid' => 3,                       //消息类型  1：系统消息  2：活动消息  3：订单消息  int
                'order_id' => $info['id'],        //订单id  int
                'j_extend' => ['pid' => 3],       //极光推送的扩展字段  array
                'm_extend' => [                   //消息列表扩展字段    array
                    'is_refund_mes' => $info['pay_status'] > 1 ? 2 : 1,
                    'order_type' => $order_type,
                    'type' => $data['type'],
                    'price' => $info['pay_price'],
                    'order_status' => $info['status'],
                    'updated_at' => date('Y-m-d H:i:s')
                ]
            ];
            push_message($message);
            return hello_success('成功！');
        }

        return hello_error('订单不存在！');
    }


}